package com.bailong.nanny.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JdbcUtils2 {

    public static final String URL = "jdbc:mysql://localhost:3306/nanny?serverTimezone=CST&useSSL=false";
    public static final String USER = "root";
    public static final String PASSWORD = "password";
    //执行器对象
    static{
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    /**
     * 查询多条数据 反射实现
     * @param clazz
     * @param sql
     * @param objects
     * @param <T>
     * @return
     */
    public static <T> List<T> queryListClazz(Class clazz, String sql, Object...objects)
    {
        try {
            Connection conn = DriverManager.getConnection(URL,USER,PASSWORD);
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            //给每个?参数赋值，这个参数是SQL里where后面接的？
            for(int i =0;i<objects.length;i++){
                preparedStatement.setObject(i+1,objects[i]);
            }
            //JDBC查询得到的结果集
            ResultSet resultSet = preparedStatement.executeQuery();
            List<T>list = new ArrayList<T>();
            while (resultSet.next()){
                //创建反射对象
                Object object = clazz.newInstance();
                Field[]fields = clazz.getDeclaredFields();
                for(Field f : fields){
                    if(f.getName().equals("serialVersionUID")){
                        continue;
                    }
                    Column colum = f.getDeclaredAnnotation(Column.class);
                    Object value = null;
                    if(colum==null){
                        //通过属性名，列名，读取一条数据
                        value = resultSet.getObject(f.getName());
                    }else {
                        //通过注解配置的列名来读取该列数据
                        value = resultSet.getObject(colum.name());
                    }
                    //通过属性名（列名）读取一条数据
                    //通过反射给属性赋值
                    f.setAccessible(true);//防止private 声明的属性无法访问
                    f.set(object,value);
                }
                //添加对象到集合中
                list.add((T)object);
            }
            return list;

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }
}
